import 'package:bottom_picker/bottom_picker.dart';
import 'package:bottom_picker/resources/arrays.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mask_text_input_formatter/mask_text_input_formatter.dart';

/// 信息提交
typedef OnSubmit = void Function(String value);

typedef OnIdCardSubmit = void Function(String gender, String birthDate, String age);

/// 性别
final _genderData = ['男', '女'];

/// 性别选项来源

final _genderItems = List<Widget>.from((_genderData.map((e) => Center(child: Text(e)))));

/// 收入来源
final _incomeRangeData = [
  '0~5000',
  '5000~8000',
  '8000~12000',
  '120000~20000',
  '20000以上',
];

/// 收入来源选项
final _incomeRangeItems = List<Widget>.from(_incomeRangeData.map((e) => Center(child: Text(e))));

/// 单位性质
final _unitNatureData = [
  '国有企业',
  '集体企业',
  '联营企业',
  '股份合作制企业',
  '私营企业',
  '个体户',
  '合伙企业',
  '有限责任公司',
  '股份有限公司',
];

/// 单位性质选项
final _unitNatureItems = List<Widget>.from(_unitNatureData.map((e) => Center(child: Text(e))));

/// 性格特征
final _characterTraitData = [
  '内向',
  '外向',
  '理性',
  '冲动',
];

/// 性格特征选项
final _characterTraitItems =
    List<Widget>.from(_characterTraitData.map((e) => Center(child: Text(e))));

/// 健康状况
final _healthStatusData = [
  '健康',
  '高血压',
  '糖尿病',
  '冠心病',
  '脑梗死',
  '脑萎缩',
  '脑出血',
  '风湿性关节炎',
  '慢性支气管炎',
  '肺气肿',
  '颈椎病',
  '慢性胃炎',
  '前列腺肥大',
  '阿尔茨海默氏症',
  '高血脂症',
  '老年性耳聋',
  '耳鸣',
  '白内障',
  '其他',
];

/// 健康状况选项
final _healthStatusItems = List<Widget>.from(_healthStatusData.map((e) => Center(child: Text(e))));

/// 客户来源
final _customerSourceData = [
  '市场拓客',
  '广告',
  '转介',
];

/// 客户来源选项
final _customerSourceItems =
    List<Widget>.from(_customerSourceData.map((e) => Center(child: Text(e))));

/// 在职人数
final employeeNumbersData = ['1~10人', '10~20人', '20~50人', '50~100人', '100~200人', '200人以上'];

/// 在职人数选项
final _employeeNumberItems =
    List<Widget>.from(employeeNumbersData.map((e) => Center(child: Text(e))));

/// 年销售额
final annualSalesData = ['0~10w', '10w~20w', '20w~30w', '30w~40w', '40w~50w', '50w~100w', '100w以上'];

/// 年销售额选项
final _annualSalesItems = List<Widget>.from(annualSalesData.map((e) => Center(child: Text(e))));

/// 经营年限
final _operatingLifeData = [
  '1年',
  '2年',
  '3年',
  '4年',
  '5年',
  '6年',
  '7年',
  '8年',
  '9年',
  '10年',
  '10年~15年',
  '15年~20年',
  '20年以上'
];

/// 经营年限选项
final _operatingLifeItems =
    List<Widget>.from(_operatingLifeData.map((e) => Center(child: Text(e))));

/// 经营方式
final _businessModeData = ['体验店', '直销', '会销'];

/// 经营方式选项
final _businessModeItems = List<Widget>.from(_businessModeData.map((e) => Center(child: Text(e))));

/// 经销商来源
final _dealerSourceData = ['招商会', '广告搜索', '转介'];

/// 经销商来源选项
final _dealerSourceItems = List<Widget>.from(_dealerSourceData.map((e) => Center(child: Text(e))));

enum SimpleItemKind {
  gender('请选择性别'), // 性别
  incomeRange('请选择收入范围'), // 收入范围
  healthStatus('请选择健康状况'), // 健康状况
  characterTrait('请选择性格特征'), // 性格特征
  unitNature('请选择单位性质'), // 单位性质
  customerSource('请选择客户来源'), // 客户来源
  employeeNumber('请选择员工数量'), // 在职人数
  annualSales('请选择年销售额'), // 年销售额
  operatingLife('请选择经营年限'), // 经营年限
  businessMode('请选择经营方式'), // 经营方式
  dealerSource('请选择经销商来源'); // 客户来源

  final String title;
  const SimpleItemKind(this.title);
}

/// 计算用户基础信息
void calculateUserBaseInfo(String idCard, OnIdCardSubmit onSubmit) {
  String gender = _calculateSex(idCard);
  DateTime? birthDate = _calculateBirthDate(idCard);
  int age = 0;
  if (birthDate != null) {
    age = _calculateAge(birthDate);
  }
  onSubmit.call(gender, birthDate.toString(), age.toString());
}

/// 根据出生日期计算年龄
/// [birthDate] 出生日期
int calculateAge(String birthString) {
  DateTime birthDate = DateTime.parse(birthString);
  return _calculateAge(birthDate);
}

/// 计算年龄
int _calculateAge(DateTime birthDate) {
  DateTime now = DateTime.now();
  var age = now.year - birthDate.year;
  if (now.month < birthDate.month || (now.month == birthDate.month && now.day < birthDate.day)) {
    age--;
  }
  return age;
}

///根据身份证号码计算性别
///身份证号码的第17位数字代表性别，奇数为男性，偶数为女性
///[idCard] 身份证号码
/// return 性别
String _calculateSex(String idCard) {
  String sexStr = idCard.substring(16, 17);
  sexStr = int.parse(sexStr) % 2 == 0 ? '女' : '男';
  return sexStr;
}

/// 根据身份证号码计算出生日期
/// 身份证号码的前6位代表出生日期
/// [idCard] 身份证号码
/// return 出生日期
DateTime? _calculateBirthDate(String idCard) {
  var birthDate = DateTime.tryParse(idCard.substring(6, 14));
  print('birthDate: $birthDate');
  return birthDate;
}

/// 打开性别选择器
void openGenderPicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _genderItems, SimpleItemKind.gender, onSubmit);
}

/// 打开收入选择器
void openIncomeRangePicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _incomeRangeItems, SimpleItemKind.incomeRange, onSubmit);
}

/// 打开健康状况选择器
void openHealthStatusPicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _healthStatusItems, SimpleItemKind.healthStatus, onSubmit);
}

/// 打开性格特征选择器
void openCharacterTraitPicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _characterTraitItems, SimpleItemKind.characterTrait, onSubmit);
}

/// 打开单位性质选择器
void openUnitNaturePicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _unitNatureItems, SimpleItemKind.unitNature, onSubmit);
}

/// 打开客户来源选择器
void openCustomerSourcePicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _customerSourceItems, SimpleItemKind.customerSource, onSubmit);
}

/// 打开在职人数选择器
void openEmployeeNumberPicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _employeeNumberItems, SimpleItemKind.employeeNumber, onSubmit);
}

/// 打开年销售额选择器
void openAnnualSalesPicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _annualSalesItems, SimpleItemKind.annualSales, onSubmit);
}

/// 打开经营年限选择器
void openOperatingLifePicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _operatingLifeItems, SimpleItemKind.operatingLife, onSubmit);
}

/// 打开经营方式选择器
void openBusinessModePicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _businessModeItems, SimpleItemKind.businessMode, onSubmit);
}

/// 打开客户来源选择器
void openDealerSourcePicker(BuildContext context, OnSubmit onSubmit) {
  _openSimpleItemPicker(context, _dealerSourceItems, SimpleItemKind.dealerSource, onSubmit);
}

/// options picker
void _openSimpleItemPicker(BuildContext context, List<Widget> items, SimpleItemKind kind,
    [OnSubmit? onSubmit]) {
  BottomPicker(
    dismissable: true,
    items: items,
    pickerTitle: Text(
      kind.title,
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
      ),
    ),
    backgroundColor: Colors.white,
    // bottomPickerTheme: BottomPickerTheme.morningSalad,
    onSubmit: (index) {
      print(index);

      switch (kind) {
        case SimpleItemKind.gender:
          onSubmit?.call(_genderData[index]);
        case SimpleItemKind.incomeRange:
          onSubmit?.call(_incomeRangeData[index]);
        case SimpleItemKind.healthStatus:
          onSubmit?.call(_healthStatusData[index]);
        case SimpleItemKind.characterTrait:
          onSubmit?.call(_characterTraitData[index]);
        case SimpleItemKind.unitNature:
          onSubmit?.call(_unitNatureData[index]);
        case SimpleItemKind.customerSource:
          onSubmit?.call(_customerSourceData[index]);
        case SimpleItemKind.employeeNumber:
          onSubmit?.call(employeeNumbersData[index]);
        case SimpleItemKind.annualSales:
          onSubmit?.call(annualSalesData[index]);
        case SimpleItemKind.operatingLife:
          onSubmit?.call(_operatingLifeData[index]);
        case SimpleItemKind.businessMode:
          onSubmit?.call(_businessModeData[index]);
        case SimpleItemKind.dealerSource:
          onSubmit?.call(_dealerSourceData[index]);
      }
      // 下个输入框
      // FocusScope.of(context).nextFocus();
    },
    buttonAlignment: MainAxisAlignment.center,
    displaySubmitButton: true,
  ).show(context);
}

enum DateItemKind {
  birthDate('请选择出生日期'), // 出生日期
  conferenceDate('请选择参会日期'), // 收入范围
  orderDate('请选择订单日期'); // 健康状况

  final String title;
  const DateItemKind(this.title);
}

/// 打开日期选择器
void openDatePicker(BuildContext context, DateItemKind kind, [OnSubmit? onSubmit]) {
  DateTime initialDateTime, minDateTime;
  switch (kind) {
    case DateItemKind.birthDate:
      initialDateTime = DateTime(1965, 6, 16);
      minDateTime = DateTime(1935, 1, 1);
    case DateItemKind.conferenceDate:
      initialDateTime = DateTime.now();
      minDateTime = DateTime(2020, 1, 1);
    case DateItemKind.orderDate:
      initialDateTime = DateTime(DateTime.now().year - 1, 6, 16);
      minDateTime = DateTime(1935, 1, 1);
  }

  BottomPicker.date(
    dismissable: true,
    pickerTitle: Text(
      '请选择出生日期',
      style: TextStyle(
        // fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Colors.black,
      ),
    ),
    dateOrder: DatePickerDateOrder.ymd,
    initialDateTime: initialDateTime,
    minDateTime: minDateTime,
    maxDateTime: DateTime.now(),
    pickerTextStyle: TextStyle(
      color: Colors.black,
      fontWeight: FontWeight.bold,
      fontSize: 12,
    ),
    onChange: (index) {
      print(index);
    },
    onSubmit: (index) {
      print(index);
      onSubmit?.call(index.toString().split(' ')[0]);
    },
    bottomPickerTheme: BottomPickerTheme.blue,
    // displayCloseIcon: false,
  ).show(context);
}

/// test
void openSecondPicer(BuildContext context) {
  _openSecondSimpleItemPicker(context, _characterTraitItems);
}

void _openSecondSimpleItemPicker(BuildContext context, List<Widget> items) {
  BottomPicker(
    items: items,
    selectedItemIndex: 1,
    pickerTitle: Text(
      'secndSimpleTitle',
      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
    ),
    pickerDescription: Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Icon(Icons.flag),
        Text(
          'secndSimpleDescription',
          textAlign: TextAlign.end,
        ),
      ],
    ),
    onChange: (index) {
      print(index);
    },
    onSubmit: (index) {
      print(index);
    },
    bottomPickerTheme: BottomPickerTheme.morningSalad,
    layoutOrientation: TextDirection.rtl,
  ).show(context);
}

void openDatePickerWithButtonStyle(BuildContext context) {
  BottomPicker.date(
    pickerTitle: Text(
      'Set your Birthday',
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Colors.blue,
      ),
    ),
    dateOrder: DatePickerDateOrder.dmy,
    minDateTime: DateTime(1935, 1, 1),
    maxDateTime: DateTime.now(),
    initialDateTime: DateTime(1965, 6, 16),
    pickerTextStyle: TextStyle(
      color: Colors.blue,
      fontWeight: FontWeight.bold,
      fontSize: 12,
    ),
    onChange: (index) {
      print(index);
    },
    onSubmit: (index) {
      print(index);
    },
    bottomPickerTheme: BottomPickerTheme.plumPlate,
    buttonStyle: BoxDecoration(
      color: Colors.blue,
      borderRadius: BorderRadius.circular(20),
      border: Border.all(
        color: Colors.blue[200]!,
      ),
    ),
    buttonWidth: 200,
    buttonContent: Padding(
      padding: const EdgeInsets.symmetric(
        horizontal: 10,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            'Select date',
            style: TextStyle(
              color: Colors.white,
            ),
          ),
          Icon(
            Icons.arrow_forward_ios,
            color: Colors.white,
            size: 15,
          ),
        ],
      ),
    ),
  ).show(context);
}

void openRangeDatePicker(BuildContext context) {
  BottomPicker.range(
    pickerTitle: Text(
      'Set date range',
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Colors.black,
      ),
    ),
    pickerDescription: Text(
      'Please select a first date and an end date',
      style: TextStyle(
        color: Colors.black,
      ),
    ),
    dateOrder: DatePickerDateOrder.dmy,
    initialSecondDate: DateTime.now().add(Duration(days: 230)),
    pickerTextStyle: TextStyle(
      color: Colors.blue,
      fontWeight: FontWeight.bold,
      fontSize: 12,
    ),
    onRangeDateSubmitPressed: (firstDate, secondDate) {
      print(firstDate);
      print(secondDate);
    },
    bottomPickerTheme: BottomPickerTheme.plumPlate,
  ).show(context);
}

void openRangeTimePicker(BuildContext context) {
  BottomPicker.rangeTime(
    pickerTitle: Text(
      'Set Time range',
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Colors.black,
      ),
    ),
    pickerDescription: Text(
      'Please select a first time and an end time',
      style: TextStyle(
        color: Colors.black,
      ),
    ),
    pickerTextStyle: TextStyle(
      color: Colors.blue,
      fontWeight: FontWeight.bold,
      fontSize: 12,
    ),
    bottomPickerTheme: BottomPickerTheme.plumPlate,
    onRangeTimeSubmitPressed: (firstDate, secondDate) {
      print(firstDate);
      print(secondDate);
    },
  ).show(context);
}

void openArabicRangeDatePicker(BuildContext context) {
  BottomPicker.range(
    pickerTitle: Text(
      'حدد النطاق الزمني',
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Colors.black,
      ),
    ),
    pickerDescription: Text(
      'الرجاء تحديد أول تاريخ وتاريخ انتهاء',
      style: TextStyle(
        color: Colors.black,
      ),
    ),
    dateOrder: DatePickerDateOrder.dmy,
    layoutOrientation: TextDirection.rtl,
    pickerTextStyle: TextStyle(
      color: Colors.blue,
      fontWeight: FontWeight.bold,
      fontSize: 12,
    ),
    onRangeDateSubmitPressed: (firstDate, secondDate) {
      print(firstDate);
      print(secondDate);
    },
    bottomPickerTheme: BottomPickerTheme.plumPlate,
  ).show(context);
}

void openTimePicker(BuildContext context) {
  BottomPicker.time(
    pickerTitle: Text(
      'Set your next meeting time',
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Colors.orange,
      ),
    ),
    onSubmit: (index) {
      print(index);
    },
    onClose: () {
      print('Picker closed');
    },
    bottomPickerTheme: BottomPickerTheme.orange,
    use24hFormat: true,
    initialTime: Time(
      minutes: 23,
    ),
    maxTime: Time(
      hours: 17,
    ),
  ).show(context);
}

void openDateTimePicker(BuildContext context) {
  BottomPicker.dateTime(
    pickerTitle: Text(
      'Set the event exact time and date',
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Colors.black,
      ),
    ),
    onSubmit: (date) {
      print(date);
    },
    onClose: () {
      print('Picker closed');
    },
    minDateTime: DateTime(1935, 1, 1),
    maxDateTime: DateTime.now(),
    initialDateTime: DateTime(1965, 6, 16),
    gradientColors: [
      Color(0xfffdcbf1),
      Color(0xffe6dee9),
    ],
  ).show(context);
}

void openDateTimePickerWithCustomButton(BuildContext context) {
  BottomPicker.dateTime(
    pickerTitle: Text(
      'Set the event exact time and date',
      style: TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 15,
        color: Colors.black,
      ),
    ),
    onSubmit: (date) {
      print(date);
    },
    onClose: () {
      print('Picker closed');
    },
    buttonSingleColor: Colors.pink,
    minDateTime: DateTime(1935, 1, 1),
    maxDateTime: DateTime.now(),
    initialDateTime: DateTime(1965, 6, 16),
    gradientColors: [
      Color(0xfffdcbf1),
      Color(0xffe6dee9),
    ],
  ).show(context);
}

void openPickerWithCustomPickerTextStyle(BuildContext context) {
  BottomPicker(
    items: [
      Center(
        child: Text('Leonardo DiCaprio'),
      ),
      Center(
        child: Text('Johnny Depp'),
      ),
      Center(
        child: Text('Robert De Niro'),
      ),
      Center(
        child: Text('Tom Hardy'),
      ),
      Center(
        child: Text('Ben Affleck'),
      ),
    ],
    pickerTitle: Text('Choose an actor'),
    titleAlignment: Alignment.center,
    pickerTextStyle: TextStyle(
      color: Colors.black,
      fontWeight: FontWeight.bold,
    ),
    closeIconColor: Colors.red,
  ).show(context);
}

class FamilyMembersMask {
  final MaskTextInputFormatter formatter;
  final FormFieldValidator<String>? validator;
  final String hint;
  final TextInputType textInputType;

  FamilyMembersMask({
    required this.formatter,
    this.validator,
    required this.hint,
    required this.textInputType,
  });
}

final fmMask = FamilyMembersMask(
  formatter: MaskTextInputFormatter(
    mask: "#儿#女",
    type: MaskAutoCompletionType.eager,
  ),
  hint: "1儿1女",
  textInputType: TextInputType.number,
);

class RegisteredCapitalMask {
  final MaskTextInputFormatter formatter;
  final FormFieldValidator<String>? validator;
  final String hint;
  final TextInputType textInputType;

  RegisteredCapitalMask({
    required this.formatter,
    this.validator,
    required this.hint,
    required this.textInputType,
  });
}

final rcMask = RegisteredCapitalMask(
  formatter: MaskTextInputFormatter(
    mask: "######### 万",
    type: MaskAutoCompletionType.eager,
  ),
  hint: "100000000 万",
  textInputType: TextInputType.number,
);
